{
  Yggdrasil functions unit
  Maintainer(s): Timothy O'Neill
}

unit UFunctions;

interface

uses
  Windows, SysUtils;

//Public functions
function GetAppVersion() : string;
function BoolToStr(TargetBoolean : boolean) : string;
function InStr(Start: Integer; sOriginal, Search : String) : Integer;
function PosRev(Needle, Haystack : String) : Integer;

implementation

function GetAppVersion() : string;
var
  Size, Size2 : DWord;
  Pt, Pt2 : Pointer;
begin
  Size := GetFileVersionInfoSize(PChar(ParamStr(0)), Size2);
  if Size > 0 then begin
    GetMem(Pt, Size);
    try
      GetFileVersionInfo(PChar(ParamStr(0)), 0, Size, Pt);
      VerQueryValue(Pt, '\', Pt2, Size2);
      with TVSFixedFileInfo(Pt2^) do begin
        Result := IntToStr(HiWord(dwFileVersionMS)) + '.' +
                  IntToStr(LoWord(dwFileVersionMS)) + '.' +
                  IntToStr(HiWord(dwFileVersionLS)) + '.' +
                  IntToStr(LoWord(dwFileVersionLS));
      end;
    finally
      FreeMem(Pt);
    end;
  end;
end;

function BoolToStr(TargetBoolean : boolean) : string;
begin
  if TargetBoolean
    then Result := 'True'
    else Result := 'False'
end;

function InStr(Start: Integer; sOriginal, Search : String) : Integer;
begin
  if (Start > Length(sOriginal)) or (start = 0) then
    Result := 0
  else
  if Pos(Search, Copy(sOriginal, Start, Length(sOriginal)-start)) = 0 then
    Result := 0
  else
    Result := Start + Pos(Search, Copy(sOriginal,
                                       Start,
                                       Length(sOriginal) - Start));
end;

function PosRev(Needle, Haystack : String) : Integer;
var
  cPos : Integer;
  nFound : BOOL;
  nLength : Integer;
begin
  nLength := length(Needle);
  cPos :=  ((Length(Haystack) - nLength) + 1);
  while True do begin
    if copy(Haystack, cPos, nLength) = Needle then break;
    cPos := (cPos - 1);
    if cPos <= 0 then begin
      cPos := 0;
      break;
    end;
  end;

  Result := cPos;
end;

end.
